<?php
/*
 * @file
 * Adds a deed into the database.
 *
 * The deed details are retreived from the POST request. The response is
 * returned in plain text:
 *  - Success : {DEED_ACTION_OK}
 *  - Failure : {DEED_ACTION_KO}{DELIMITER_DEED_ACTION_RESPONSE}<error message>
 *
 * Usage:
 *  - Submit a POST request to this page.
 *
 * GET Parameter(s):
 *  - See 'js_params_get.php'.
 *
 * POST Parameter(s):
 *  - {NAME_DEED_ADD_TYPE_ID} : Deed type ID.
 *  - {NAME_DEED_ADD_INPUT}   : Delimited user input.
 *
 * Global variable(s) set:
 *  - None.
 *
 * Global variable(s) unset:
 *  - None.
 *
 * Exception(s):
 *  - None.
 *
 * This file includes/requires:
 *  - h_greenindeed.php
 *  - h_deed.php
 *  - fb_user_uid.php
 *  - db_mysql_greenindeed.php
 *  - db_mysql_connect.php
 *  - db_mysql_disconnect.php
 */

// header file(s) ==============================================================
require_once "h_greenindeed.php";
require_once "h_deed.php";


// implementation ==============================================================
try {
  // retreive user id
  require_once $PATH_COMMON . "php/fb_user_uid.php";

  // retreive post parameters
  $deed_type_id           = $_POST[NAME_DEED_ADD_TYPE_ID];
  $deed_statement_replace = $_POST[NAME_DEED_ADD_INPUT];

  // connect to database
  require_once "db_mysql_greenindeed.php";
  require_once $PATH_COMMON . "php/db_mysql_connect.php";

  // check user exists
  $user_found = mysql_query(
    "select USER_ID from USERS where USER_ID = '" . $fb_uid . "'"
  );
  $result    = false;
  $sql_error = null;
  if (0 == mysql_num_rows($user_found)) {
    // add new user
    $result = mysql_query(
      "insert into USERS (USER_ID) values ('" . $fb_uid . "')"
    );
    $sql_error = mysql_error();
  } else {
    $result = true;
  }

  if (true == $result) {
    // add deed
    $result = mysql_query("
      insert into DEEDS
        (USER_ID, DEED_TYPE_ID, DEED_STATEMENT_REPLACE, DEED_DATETIME, LOCALE)
      values (
        '" . $fb_uid                 . "',
        '" . $deed_type_id           . "',
        '" . $deed_statement_replace . "',
        now(),
        '" . $locale_user . "'
      )
    ");
    $sql_error = mysql_error();
  }

  // disconnect from database
  require_once $PATH_COMMON . "php/db_mysql_disconnect.php";

  // test result
  if (true == $result) {
    // return ok flag
    echo DEED_ACTION_OK;
  } else {
    // return ko flag and error message
    echo DEED_ACTION_KO . DELIMITER_DEED_ACTION_RESPONSE . $sql_error;
  }
} catch (Exception $ex) {
  // return ko flag and exception message
  echo DEED_ACTION_KO . DELIMITER_DEED_ACTION_RESPONSE . $ex->getMessage();
}
?>
